package com.zt.bus.line.service;

import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zt.bus.assistant.model.LineStop;
import com.zt.bus.constant.BusConstant;
import com.zt.bus.line.model.Dispatch;
import com.zt.bus.line.model.Driver;
import com.zt.bus.line.model.LinePlan;
import com.zt.bus.line.model.Vehicle;
import com.zt.bus.order.inter.OrderDetailMapper;
import com.zt.bus.order.model.Order;
import com.zt.bus.order.model.OrderDetail;
import com.zt.bus.order.service.OrderService;
import com.zt.bus.sms.service.SendCodeService;
import com.zt.bus.util.DesUtils;
import com.zt.servlet.Response;
import com.zt.system.model.BusinessException;
import com.zt.system.service.BaseService;
import com.zt.util.DateUtil;
import com.zt.util.PropertiesUtil;
import com.zt.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 司机端接口
 * 
 * @author Administrator
 *
 */
@Service
public class DriverInterService extends BaseService {

	@Autowired
	private OrderDetailMapper orderDetailMapper;
	@Autowired
	private VehicleService vehicleService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private DriverService driverService;
	@Autowired
	private LineService lineService;
	@Autowired
	private LinePlanService linePlanService;
	@Autowired
	private DispatchService dispatchService;
	@Autowired
	private SendCodeService sendCodeService;

	// 新线招募取消模版id
	public static final String REMIND_UNCHECKED = PropertiesUtil.getProperty("remind_unchecked");

	/**
	 * 司机端登录接口
	 * 
	 * @param driverNo
	 *            司机编号
	 * @param driverPhone
	 *            司机手机号
	 * @return
	 */
	public JSONObject driverLogin(String driverNo, String driverPhone) {
		if (StringUtil.isEmpty(driverNo)) {
			throw new BusinessException("司机登录参数错误!");
		}
		if (StringUtil.isEmpty(driverPhone)) {
			throw new BusinessException("请司机登录参数错误!");
		}

		JSONObject result = new JSONObject();
		Driver driver = driverService.getByDriverNo(driverNo);
		if (driver == null) {
			throw new BusinessException("司机信息不存在!");
		} else {
			if (driver.getDriverPhone().equals(driverPhone)) {
				result.put("driverName", driver.getDriverName());
			} else {
				throw new BusinessException("手机号或编号不正确!");
			}
		}
		return result;
	}

	/**
	 * 司机排班计划列表
	 * 
	 * @param driverNo
	 * @return
	 */
	public JSONArray getDriverSchedule(String driverNo) {
		Date date = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTime(date); 
		cal.add(cal.DATE,-3);//把日期往后增加一天.整数往后推,负数往前移动 
	    date=cal.getTime();   //这个时间就是日期往后推一天的结果 
	    String queryDate = DateUtil.formatDate(date);
		
		if (StringUtil.isEmpty(driverNo)) {
			throw new BusinessException("请传入司机编号!");
		}

		JSONArray dateArray = new JSONArray();
		// 获得司机所有的分配信息
		StringBuffer sqlBuffer = new StringBuffer(
				"select lp.DEPART_TIME,l.C_LINE_TYPE,l.MILEAGE, pd.*  from DZ_DISPATCH pd ");
		sqlBuffer.append(" LEFT JOIN DZ_LINE_PLAN lp on pd.PLAN_ID=lp.PLAN_ID");
		sqlBuffer.append(" LEFT JOIN DZ_LINE l on pd.LINE_ID=l.LINE_ID");
		sqlBuffer.append(" where pd.DRIVER_NO= '" + driverNo + "' ");
		sqlBuffer.append(" and pd.DEPART_DATE >'" + queryDate + "' ");
		sqlBuffer.append(" order by pd.DEPART_DATE");

		JSONArray palnDriverArray = this.query(sqlBuffer.toString());

		JSONObject json = new JSONObject();
		for (int i = 0; i < palnDriverArray.size(); i++) {
			JSONObject palnDriverJson = palnDriverArray.getJSONObject(i);
			String planId = palnDriverJson.getString("planId");
			String lineId = palnDriverJson.getString("lineId");
			String lineName = palnDriverJson.getString("lineName");
			String lineType = palnDriverJson.getString("lineType");
			String vehicleNo = palnDriverJson.getString("vehicleNo");
			String departDate = palnDriverJson.getString("departDate");
			String departTime = palnDriverJson.getString("departTime");
			String mileage = palnDriverJson.getString("mileage");// 里程

			json.put("date", DateUtil.formatDate(DateUtil.parse(departDate)));
			json.put("planId", planId);
			json.put("lineId", lineId);
			json.put("lineName", lineName);
			json.put("lineType", lineType);// 线路类型：1-定制公交、2-职工专线
			json.put("vehicleNo", vehicleNo);

			// 获得发车数量
			List<Dispatch> list = dispatchService.getByPlanIdAndDepartDate(planId, DateUtil.parse(departDate));
			json.put("vehicleNumber", list.size());// 发车数量

			json.put("departTime", departTime);// 发车时间
			json.put("mileage", mileage); // 里程

			// 计算预定人数
			int seatNum = 0;
			for (Dispatch dispatch : list) {
				Vehicle vehicle = vehicleService.getByVehicleNo(dispatch.getVehicleNo());
				seatNum += vehicle.getSeatNum();
			}

			// 通过方案id找到订单信息
			List<OrderDetail> orderDetailList = orderDetailMapper.selectByPlanIdAndRideDate(planId,
					DateUtil.parse(departDate));
			json.put("passengerNumber", orderDetailList.size());
			json.put("seatNum", seatNum);
			dateArray.add(json);
		}
		return dateArray;
	}

	/**
	 * 已上车、未上车乘客信息
	 * 
	 * @param planId
	 * @param rideDate
	 * @param isChecked
	 *            是否验票
	 * @return
	 */
	public JSONArray getPassengers(String planId, Date rideDate, boolean isChecked) {
		JSONArray passengers = new JSONArray();
		// 通过方案id找到订单信息
		List<OrderDetail> orderDetailList = orderDetailMapper.selectByPlanIdAndRideDate(planId, rideDate);

		LinePlan linePlan = linePlanService.getById(planId);
		if (linePlan == null) {
			throw new BusinessException("线路方案不存在!");
		}
		// 通过订单找到订单明细
		for (OrderDetail orderDetail : orderDetailList) {
			JSONObject json = new JSONObject();
			json.put("passengerName", orderDetail.getPassengerName());
			json.put("passengerPhone", orderDetail.getPassengerPhone());
			json.put("reminded", BusConstant.OrderDetailStatus.REMINDED.equals(orderDetail.getStatus()) ? true : false);
			LineStop lineStop = lineService.getStop(orderDetail.getOnStopId());
			if (lineStop == null) {
				json.put("onStopName", "未命名站点");
			} else {
				json.put("onStopName", lineStop.getStopName());
			}
			if (!isChecked) {
				if (!BusConstant.OrderDetailStatus.CHECKED.equals(orderDetail.getStatus())) {// 未验票
					passengers.add(json);
				}
			} else {
				if (BusConstant.OrderDetailStatus.CHECKED.equals(orderDetail.getStatus())) {// 已验票
					passengers.add(json);
				}
			}
		}
		return passengers;
	}

	/**
	 * 用户短信提醒
	 * 
	 * @param passengerPhone
	 * @param planId
	 * @param rideDate
	 */
	public void remindPassenger(String passengerPhone, String planId, Date rideDate) {
		// 修改乘客状态
		List<OrderDetail> orderDetailList = orderDetailMapper.selectByPlanIdAndPassengerPhoneAndRideDate(planId, passengerPhone,
				rideDate);
		for (OrderDetail orderDetail : orderDetailList) {
			// 发送退款申请短信
			String orderId = orderDetail.getOrderId();
			Order order = orderService.getById(orderId);
			JSONObject json = new JSONObject();
			json.put("lineName", order.getLineName());
			json.put("departTime", order.getDepartTime());
			boolean result = sendCodeService.sendSms(orderId, passengerPhone, json.toString(), "未验票乘客短信提醒",
					REMIND_UNCHECKED);
			if (result) {
				orderDetail.setStatus(BusConstant.OrderDetailStatus.REMINDED);
				orderDetailMapper.updateByPrimaryKey(orderDetail);
			}
			break;// 同一个手机号可以订多次，只发一条短信
		}
	}

	/**
	 * 判断是否为该司机对应的乘客
	 * 
	 * @param orderId
	 * @param driverNo
	 * @return
	 */
	public boolean isMatching(String orderId, String driverNo) {
		boolean flag = false;
		Date date = new Date();
		Order order = orderService.getById(orderId);
		if (order == null) {
			throw new BusinessException("订单不存在");
		}
		List<Dispatch> dispatchList = dispatchService.getByPlanIdAndDepartDate(order.getPlanId(), date);
		for (Dispatch dispatch : dispatchList) {
			if (dispatch.getDriverNo().equals(driverNo)) {
				flag = true;
				break;
			}
		}
		return flag;
	}

	/**
	 * 扫码事件
	 *
	 * @param orderStr
	 * @return
	 */
	public JSONObject scanCode(String orderStr, String driverNo) {
		if (StringUtil.isEmpty(orderStr) || StringUtil.isEmpty(driverNo)) {
			return Response.responseError("缺少请求参数!");
		}
		// 解密字符串
		String decryptStr = null;
		try {
			DesUtils desUtils = new DesUtils();
			decryptStr = desUtils.decrypt(orderStr);
		} catch (Exception e) {
			e.printStackTrace();
			return Response.responseError("解密异常");
		}
		JSONObject decryptJson = JSONObject.fromObject(decryptStr);
		if (decryptJson == null || "{}".equals(decryptJson)) {
			return Response.responseError("解密后的数据异常!");
		}
		long encryptDate = Long.parseLong(decryptJson.getString("encryptDate"));
		if (new Date().getTime() - encryptDate > 10 * 60 * 1000) { // 二维码10分钟过期
			return Response.responseError("二维码已过期!");
		}

		// todo 判断是否为该司机对应的乘客
		if (!isMatching(decryptJson.getString("orderId"), driverNo)) {
			return Response.responseError("请乘坐与短信对应的车辆!");
		}
		// 判断订单明细状态是否为已扫码状态
		Date date = DateUtil.parse(DateUtil.formatDate(new Date()));
		OrderDetail orderDetail = orderDetailMapper.selectByOrderIdAndPassengerPhoneAndRideDate(
				decryptJson.getString("orderId"), decryptJson.getString("passengerPhone"), date);

		// 判断是否已经扫过码
		if (orderDetail.getStatus().equals(BusConstant.OrderDetailStatus.CHECKED)) {
			return Response.responseError("二维码已使用!");
		}

		// 判断订单明细状态是否为支付成功状态，只有支付成功状态才能乘车
		if (!orderDetail.getStatus().equals(BusConstant.PaymentStatus.PAYMENT_SUCCESSFUL)) {
			return Response.responseError("正在退款中!");
		}

		// 将订单详情修改为已验票
		orderDetailMapper.updateStatusById(orderDetail.getId(), BusConstant.OrderDetailStatus.CHECKED);
		return Response.responseSuccess("扫码成功!");
	}
}